package com.dick.base.service;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dick.base.util.ServletUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Service
public class FileService {

    @Value("${files.directory}")
    private String fileDirectory;

    /**
     * 上传文件
     * @param file
     * @throws IOException
     */
    public Long uploadFile(MultipartFile file) throws IOException {
        Long fileId = IdWorker.getId();
        File fileDest = new File(fileDirectory, fileId.toString());
        if (!fileDest.exists()) {
            fileDest.createNewFile();
        }
        file.transferTo(fileDest);
        return fileId;
    }

    /**
     * 下载文件
     * @param fileId
     */
    public void downloadFile(Long fileId) throws IOException {
        File fileDest = new File(fileDirectory, fileId.toString());
        HttpServletResponse response = ServletUtil.currentResponse();
        response.setContentType("application/blob");

//        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(fileDest));
            response.setHeader("Content-Length", String.valueOf(bis.available()));
            StreamUtils.copy(bis, outputStream);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {

                }

            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e) {

                }
            }
        }
    }
}
